<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        class LinkList {
            head = null
            length = 0

            createNode(data) {
                return {
                    data, 
                    next: null
                }
            }

            append(element){
                //首先先创建一个节点
                const node = this.createNode(element)

                // 如果是第一个节点
                if (this.length === 0) {
                    this.head = node
                } else {
                    // 不是第一个节点
                    let current = this.head
                    // 判断下一个节点是否为null
                    while(current.next) {
                        current = current.next
                    }
                    current.next = node
                }
                this.length += 1
            }

            insert(position, element) {
                // 插入方法
                // 边界判断
                if (position < 0 || position > this.length) {
                    return false
                }
                // 创建新节点
                let newNode = this.createNode(element)
                // 插入的是头部的时候
                if (position === 0) {
                    newNode.next = this.head
                    this.head = newNode
                }
                // 如果是中间元素插入
                let index = 0
                let current = this.head
                let previous = null
                while (index++ < position) {
                    previous = current
                    current = current.next
                }
                newNode.next = current
                previous.next = newNode
            
                this.length += 1

                return true
            }
            get(position) {}
            indexOf(element) {}
            update(position) {}
            removeAt(position) {}
            remove(element) {}
            isEmpty() {}
            size() {}
            toString() {
                let current = this.head
                let str = ''
                while(current) {
                    str += current.data + ' '
                    current = current.next
                }
                return str
            }
            
        }

        let list = new LinkList()
        list.append('aaa')
        list.append('bbb')
        list.append('ccc')
        list.insert(1,'ddd')
        console.log(list.toString())
    </script>
</body>
</html>